package fun.ticsmyc.rpc.client.transport.netty.codec;

import fun.ticsmyc.rpc.common.entity.RpcRequest;
import fun.ticsmyc.rpc.common.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 客户端编码器： 将RpcRequest转为Byte数组，提供给下一个Handler使用
 * @author Ticsmyc
 * @date 2020-10-26 10:42
 */
public class RequestEncoder extends MessageToByteEncoder<RpcRequest> {
    private static final Logger logger = LoggerFactory.getLogger(RequestEncoder.class);
    private Serializer serializer;

    private final int MAGIC_NUMBER = 0xCAFEBABE;
    private final byte CURRENT_PROTOCOL_VERSION = 1;

    public RequestEncoder(Serializer serializer){
        this.serializer = serializer;
    }

    // 格式 ：  魔数 + 序列化器编号 + 协议版本 + 消息体长度 + 消息体
    @Override
    protected void encode(ChannelHandlerContext ctx, RpcRequest msg, ByteBuf out) {
        byte[] serialize = serializer.serialize(msg);

        //魔数： 4 byte
        out.writeInt(MAGIC_NUMBER);
        //协议版本：1 byte
        out.writeByte(CURRENT_PROTOCOL_VERSION);
        //序列化器编号： 1 byte
        out.writeByte(serializer.getId());
        //消息体长度： 4 byte
        out.writeInt(serialize.length);
        //消息体
        out.writeBytes(serialize);
        logger.debug("请求包大小："+(serialize.length+10));
    }
}
